import React, { Component } from "react";
import { EditorState, convertToRaw, ContentState } from "draft-js";
import { Editor } from "react-draft-wysiwyg";
import "./react-draft-wysiwyg.css";
import draftToHtml from "draftjs-to-html";
import PropTypes from "prop-types";
// html 转换为 draft
import htmlToDraft from "html-to-draftjs";

//富文本编辑器html-to-draftjs
export default class RichTextEditor extends Component {
  static propTypes = {
    detail: PropTypes.string.isRequired,
  };
  state = {
    editorState: [],
  };
  constructor(props) {
    super(props);
    const html = this.props.detail;
    console.log(66666, html);
    if (html) {
      const contentBlock = htmlToDraft(html);
      if (contentBlock) {
        const contentState = ContentState.createFromBlockArray(
          contentBlock.contentBlocks
        );
        const editorState = EditorState.createWithContent(contentState);
        this.state = { editorState };
      }
    } else {
      this.state = {
        editorState: EditorState.createEmpty(),
      };
    }
  }

  onEditorStateChange = (editorState) => {
    this.setState({ editorState });
  };

  getDetail = () => {
    //返回HTML格式数据
    return draftToHtml(
      convertToRaw(this.state.editorState.getCurrentContent())
    );
  };
  render() {
    const { editorState } = this.state;
    return (
      <div>
        <Editor
          editorState={editorState}
          editorStyle={{ border: "1px solid black", minHeight: 200 }}
          onEditorStateChange={this.onEditorStateChange}
        />
        {/* <textarea
          disabled
          value={draftToHtml(convertToRaw(editorState.getCurrentContent()))}
        ></textarea> */}
      </div>
    );
  }
}
